// heap5.hxx


#ifndef _BLOGS_HEAP5
#define _BLOGS_HEAP5


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"
#include "std_out.hxx"


namespace blogs
{


class Heap5
{

  private:

    /*
     * pstns[]
     *  array index is the position in level of binary tree. 0 is NOT used.
     *  array value is the position in preorder of binary tree. 0 is NOT used.
     *
     */
    static
    void
    __position__(int k, int * p, Array<int> & pstns)
    {
        if (k >= pstns.size()) return;
        pstns[k] = ++*p;
        __position__(k*2,   p, pstns);
        __position__(k*2+1, p, pstns);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __sink__(Array<_T> & a, int k, int n, Array<int> & pstns)
    {
        while (2*k <= n) {
            int j = 2*k;
            if (j < n && __less__(a[pstns[j]-1], a[pstns[j+1]-1])) ++j;
            if (!__less__(a[pstns[k]-1], a[pstns[j]-1])) break;
            __exch__(a, k, j, pstns);
            k = j;
        }
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __exch__(Array<_T> & a, int i, int j, Array<int> & pstns)
    {
        _T t = a[pstns[i]-1];
        a[pstns[i]-1] = a[pstns[j]-1];
        a[pstns[j]-1] = t;
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        int N = a.size();
        Array<int> pstns(N+1);
        int p = 0;
        __position__(1, &p, pstns);
        for (int k = N/2; k >= 1; --k)
            __sink__(a, k, N, pstns);
        while (N > 1) {
            __exch__(a, 1, N, pstns);
            --N;
            __sink__(a, 1, N, pstns);
        }
        Array<_T> t(a.size());
        for (int i = 0; i < a.size(); ++i) t[i] = a[i];
        for (int i = 0; i < a.size(); ++i) a[i] = t[pstns[i+1]-1];
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }

};


} // end of namespace blogs


#endif

